//
//  QXN_ToolKit.m
//  QXN_Bird
//
//  Created by chou on 15/7/1.
//  Copyright (c) 2015年 chou. All rights reserved.
//

#import "AKToolKit.h"


@implementation AKToolKit

+ (void)setButtonTitleColor:(UIColor *)color SelectColor:(UIColor *)selectColor Button:(UIButton *)button
{
    [button setTitleColor:color forState:UIControlStateNormal];
    [button setTitleColor:selectColor forState:UIControlStateSelected];
}


+ (UILabel *)createLabel:(CGRect)frame andTextColor:(UIColor *)color
                 andText:(NSString *)text andFont:(UIFont *)font
                andAlign:(NSTextAlignment)align Tag:(int)tag
{
    UILabel *nameLabel = [[UILabel alloc] init];
    nameLabel.backgroundColor = [UIColor clearColor];
    nameLabel.text = text;
    nameLabel.textColor = color;
    nameLabel.tag = tag;
    nameLabel.font = font;
    nameLabel.frame = frame;
    nameLabel.textAlignment = align;
    return nameLabel;
}

+ (UIButton *)createButton:(CGRect)frame Title:(NSString *)title
                TitleColor:(UIColor *)color Bgimage:(NSString *)imgname
                       Tag:(int)tag Font:(UIFont *)font
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:color forState:UIControlStateNormal];
    [btn.titleLabel setFont:font];
    btn.frame = frame;
    [btn setBackgroundImage:[UIImage imageNamed:imgname] forState:UIControlStateNormal];
//    [btn setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@_pressed",imgname]] forState:UIControlStateHighlighted];
    btn.tag = tag;
    return btn;
}

+ (UIView *)createView:(CGRect)frame BackColor:(UIColor *)color Tag:(int)tag
{
    UIView *view = [[UIView alloc] initWithFrame:frame];
    view.backgroundColor = color;
    view.tag = tag;
    return view;
}

+ (float) heightForString:(NSString *)value fontSize:(float)fontSize andWidth:(float)width
{
    NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:fontSize]};
    CGSize sizeToFit = [value boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
    return sizeToFit.height + 5;
}

+ (float)widthForString:(NSString *)value fontSize:(float)fontSize andHeight:(float)height
{
    NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:fontSize]};
    CGSize sizeToFit = [value boundingRectWithSize:CGSizeMake(ScreenWidth - 11 * 2, height) options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
    return sizeToFit.width;
}

+ (UIImage *)ellipseImage: (UIImage *) image withInset: (CGFloat) inset withBorderWidth:(CGFloat)width withBorderColor:(UIColor*)color
{
    UIGraphicsBeginImageContext(image.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGRect rect = CGRectMake(inset, inset, image.size.width - inset * 2.0f , image.size.height - inset * 2.0f);
    
    CGContextAddEllipseInRect(context, rect);
    CGContextClip(context);
    [image drawInRect:rect];
    
    if (width > 0) {
        CGContextSetStrokeColorWithColor(context, color.CGColor);
        CGContextSetLineCap(context,kCGLineCapButt);
        CGContextSetLineWidth(context, width);
        CGContextAddEllipseInRect(context, CGRectMake(inset + width/2, inset +  width/2, image.size.width - width- inset * 2.0f, image.size.height - width - inset * 2.0f));//在这个框中画圆
        
        CGContextStrokePath(context);
    }
    
    
    UIImage *newimg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newimg;
}

+ (CGFloat)heightFromUITextView:(NSString *)text Frame:(CGRect)frame
{
    UITextView *textView = [[UITextView alloc] init];
    textView.userInteractionEnabled = NO;
    textView.frame = frame;
    textView.textColor = RGBHEX(0x868686);
    textView.font = [UIFont systemFontOfSize:12];
    NSMutableAttributedString * attributedString1 = [[NSMutableAttributedString alloc] initWithString:text];
    NSMutableParagraphStyle * paragraphStyle1 = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle1 setLineSpacing:5];
    [attributedString1 addAttribute:NSParagraphStyleAttributeName value:paragraphStyle1 range:NSMakeRange(0, [text length])];
    [textView setAttributedText:attributedString1];
    [textView sizeToFit];
    textView.text = text;
    
    return textView.frame.size.height;
}

+ (UIImage *)createImageWithColor:(UIColor *)color{
    CGRect rect = CGRectMake(0.0f,0.0f,1.0f,1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

+ (void)ButtonTextLeftStyle:(UIButton *)button
{
    [button setTitleColor:RGBHEX(0xC7C7CD) forState:UIControlStateNormal];
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    button.titleEdgeInsets = UIEdgeInsetsMake(2, 0, 0, 0);
}

+ (NSArray *)arrayFromPlist:(NSString *)filename
{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:filename ofType:@"plist"];
    
    NSArray *array = [NSArray arrayWithContentsOfFile:filePath];
    
    return array;
}

+ (NSDictionary *)dictionaryFromPlist:(NSString *)filename
{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:filename ofType:@"plist"];
    
    NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:filePath];
    
    return dictionary;
}

+ (int)getIdByName:(NSString *)title filename:(NSString *)filename
{
    int fileid = 0;
    NSString *filePath = [[NSBundle mainBundle] pathForResource:filename ofType:@"plist"];
    
    NSArray *array = [NSArray arrayWithContentsOfFile:filePath];
    for (int i = 0; i < array.count; i++)
    {
        NSDictionary *dictionary = (NSMutableDictionary *)array[i];
        if ([dictionary[@"title"] isEqualToString:title])
        {
            fileid = [dictionary[@"id"] intValue];
            break;
        }
    }
    return fileid;
}

+ (NSString *)getNameById:(int)ID filename:(NSString *)filename
{
    NSString *title = @"";
    NSString *filePath = [[NSBundle mainBundle] pathForResource:filename ofType:@"plist"];
    
    NSArray *array = [NSArray arrayWithContentsOfFile:filePath];
    for (int i = 0; i < array.count; i++)
    {
        NSDictionary *dictionary = (NSMutableDictionary *)array[i];
        if ([dictionary[@"id"] intValue] == ID)
        {
            title = dictionary[@"title"];
            break;
        }
    }
    return title;
}

+ (int)returnCityIdFromCityName
{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"city" ofType:@"txt"];
    NSData *data = [[NSData alloc] initWithContentsOfFile:filePath];
    NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    
    for (int i = 0; i < array.count; i++)
    {
//        NSDictionary *dictoinary = array[i];
//        if ([dictoinary[@"title"] isEqualToString:GETCITYNAME])
//        {
//            return [dictoinary[@"id"] intValue];
//        }
    }
    return 0;
}

+ (NSString *)getCityNameById:(int)cityid
{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"city" ofType:@"txt"];
    NSData *data = [[NSData alloc] initWithContentsOfFile:filePath];
    NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    
    for (int i = 0; i < array.count; i++)
    {
        NSDictionary *dictoinary = array[i];
        if ([dictoinary[@"id"] intValue] == cityid)
        {
            return dictoinary[@"title"];
        }
    }
    return @"";
}

+ (NSString *)formatNSDate:(NSDate *)date formatter:(NSString *)format
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format];
    NSString *currentDateStr = [dateFormatter stringFromDate:date];
    return currentDateStr;
}

//+ (int)returnUserId
//{
//    return [[QXN_User shareUsers] userid];
//    return 0;
//}

+ (NSDate *)convertDateFromString:(NSString *)dateStr
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:dateStr];
    return date;
}


+ (UIImage*)circleImage:(UIImage*)image withParam:(CGFloat)inset
{
    
    UIGraphicsBeginImageContext(image.size);
    
    CGContextRef context =UIGraphicsGetCurrentContext();
    
    //圆的边框宽度为2，颜色为红色
    
    CGContextSetLineWidth(context,2);
    
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
    
    CGRect rect = CGRectMake(inset, inset, image.size.width - inset *2.0f, image.size.height - inset *2.0f);
    
    CGContextAddEllipseInRect(context, rect);
    
    CGContextClip(context);
    
    //在圆区域内画出image原图
    
    [image drawInRect:rect];
    
    CGContextAddEllipseInRect(context, rect);
    
    CGContextStrokePath(context);
    
    //生成新的image
    
    UIImage *newimg = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return newimg;
}

+ (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}

+(NSString*)getChineseCalendarWithDate:(NSDate *)date{
    
    NSArray *chineseMonths=[NSArray arrayWithObjects:
                            @"正月", @"二月", @"三月", @"四月", @"五月", @"六月", @"七月", @"八月",@"九月", @"十月", @"冬月", @"腊月", nil];
    NSArray *chineseDays=[NSArray arrayWithObjects:
                          @"初一", @"初二", @"初三", @"初四", @"初五", @"初六", @"初七", @"初八", @"初九", @"初十",@"十一", @"十二", @"十三", @"十四", @"十五", @"十六", @"十七", @"十八", @"十九", @"二十",@"廿一", @"廿二", @"廿三", @"廿四", @"廿五", @"廿六", @"廿七", @"廿八", @"廿九", @"三十",  nil];
    
    NSCalendar *localeCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierChinese];
    
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;
    
    NSDateComponents *localeComp = [localeCalendar components:unitFlags fromDate:date];
    
    NSString *m_str = [chineseMonths objectAtIndex:localeComp.month-1];
    NSString *d_str = [chineseDays objectAtIndex:localeComp.day-1];
    
    NSString *chineseCal_str =[NSString stringWithFormat: @"%@ 农历%@%@",[self getWeekDayByDate:date],m_str,d_str];

    return chineseCal_str;  
}

+ (NSString *)getWeekDayByDate:(NSDate *)date{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *weekComp = [calendar components:NSCalendarUnitWeekday fromDate:date];
    NSInteger weekDayEnum = [weekComp weekday];
    NSString *weekDays = nil;
    switch (weekDayEnum) {
        case 1:
            weekDays = @"星期日";
            break;
        case 2:
            weekDays = @"星期一";
            break;
        case 3:
            weekDays = @"星期二";
            break;
        case 4:
            weekDays = @"星期三";
            break;
        case 5:
            weekDays = @"星期四";
            break;
        case 6:
            weekDays = @"星期五";
            break;
        case 7:
            weekDays = @"星期六";
            break;
        default:
            break;
    }
    return weekDays;
}

+ (NSArray *)allcityByText
{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"city" ofType:@"txt"];
    NSData *data = [[NSData alloc] initWithContentsOfFile:filePath];
    NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    return array;
}


+ (NSArray *)getSearchHistory
{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"history" ofType:@"plist"];
    
    NSFileManager*fileManager =[NSFileManager defaultManager];
    NSError*error;
    NSArray*paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString*documentsDirectory =[paths objectAtIndex:0];
    
    NSString*txtPath =[documentsDirectory stringByAppendingPathComponent:@"history.plist"];
    
    if(![fileManager fileExistsAtPath:txtPath]){
        [fileManager copyItemAtPath:filePath toPath:txtPath error:&error];
    }
    
    NSArray *array = [NSArray arrayWithContentsOfFile:txtPath];
    
    return array;
}

+ (void)writeHistory:(NSString *)keyword
{
    NSMutableArray *array = [NSMutableArray new];
    NSArray *harray = [self getSearchHistory];
    for (int i = 0; i < harray.count; i++)
    {
        [array addObject:harray[i]];
    }
    
    [array addObject:keyword];
    
    NSArray*paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString*documentsDirectory =[paths objectAtIndex:0];
    
    NSString *filepath =[documentsDirectory stringByAppendingPathComponent:@"history.plist"];
    
    [array writeToFile:filepath atomically:YES];
}

+ (NSString*)DataTOjsonString:(id)object
{
    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    if (! jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"jsonString:%@",jsonString);
    }
    return jsonString;
}

+ (NSDate *)dateFromString:(NSString *)dateString{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
    NSDate *destDate= [dateFormatter dateFromString:dateString];
    
    return destDate;
}


+ (BOOL)isAgentApp {
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    CFShow((__bridge CFTypeRef)(infoDictionary));
    // 项目名称
    NSString *app_Name = [infoDictionary objectForKey:@"CFBundleExecutable"];
    if ([app_Name isEqualToString:@"QXN_Bird"]) {//用户端
        return false;
    }else {//经纪人端
        return true;
    }
}
@end
